package com.dries.chat.netty;

import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description: 用户ID和channel 关联关系处理
 * @Author ZSY
 * @createTime 2020/7/8 16:21
 */
@Slf4j
public class UserChannelRel {

    private static final Map<String, Channel> manager = new ConcurrentHashMap<>();

    /**
     * 判断一个通道是否有用户在使用
     * 可做信息转发时判断该通道是否合法
     * @param channel
     * @return
     */
    public static boolean hasUser(Channel channel) {
        AttributeKey<String> key = AttributeKey.valueOf("user");
        //netty移除了这个map的remove方法,这里的判断谨慎一点
        return (channel.hasAttr(key) || channel.attr(key).get() != null);
    }

    public static void put(String senderId, Channel channel) {

        // TODO 验证用户是否登录 （redis）
        manager.put(senderId, channel);
        AttributeKey<String> key = AttributeKey.valueOf("user");
        channel.attr(key).set(senderId);

    }

    public static Channel get(String senderId) {
        return manager.get(senderId);
    }

    public static void remove(String senderId) {
        manager.remove(senderId);
    }

    public Integer size() {
        return manager.size();
    }

    public static void output() {
        for (Map.Entry<String, Channel> entry : manager.entrySet()) {
            log.info("UserID: {}", entry.getKey());
            log.info("ChannelID: {}", entry.getValue().id().asLongText());
        }
    }

}
